// log.go
//日志handler
package componnet

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	_ "path/filepath"
	"syscall"
)

//异常日志handler
var Elogger *log.Logger

//主日志handler
var Slogger *log.Logger

//API日志handler
var Alogger *log.Logger

//数据库日志handler,为兼容xorm的日志接口
var SQLlogger *os.File

//cronjob日志
var Clogger *log.Logger

func init() {
	initServiceHandler()
	initApiHandler()
	initErrorHandler()
	initSQLHandler()
	initCloggerHandler()
}

//初始化主日志handler
func initServiceHandler() {
	logFile, err := AppConfig.GetValue(ENV, "service_log")
	if err != nil {
		logFile = "logs/service.log"
	}
	checkFolder(logFile)
	file, _ := os.Create(logFile)
	Slogger = log.New(file, "[main]", log.LstdFlags)
}

//初始化API日志handler
func initApiHandler() {
	logFile, err := AppConfig.GetValue(ENV, "api_log")
	if err != nil {
		logFile = "logs/api.log"
	}
	checkFolder(logFile)
	file, cerr := os.Create(logFile)
	if cerr != nil {
		fmt.Println(cerr)
	}
	Alogger = log.New(file, "[API]", log.LstdFlags|log.Lshortfile)
}

//初始化错误handler
func initErrorHandler() {
	logFile, err := AppConfig.GetValue(ENV, "error_log")
	if err != nil {
		logFile = "logs/error.log"
	}
	checkFolder(logFile)
	file, _ := os.Create(logFile)
	Elogger = log.New(file, "[error]", log.Llongfile)
}

//初始化sql日志handler
func initSQLHandler() {
	logFile, err := AppConfig.GetValue(ENV, "sql_log")
	if err != nil {
		logFile = "logs/sql.log"
	}
	checkFolder(logFile)
	file, _ := os.Create(logFile)
	SQLlogger = file
}

//初始化cronjob日志
func initCloggerHandler() {
	logFile, err := AppConfig.GetValue(ENV, "cron_log")
	if err != nil {
		logFile = "logs/cron.log"
	}
	checkFolder(logFile)
	file, _ := os.Create(logFile)
	Clogger = log.New(file, "[cron]", log.LstdFlags)
}

func checkFolder(name string) {
	absPath, aerr := filepath.Abs(name)
	if aerr != nil {
		fmt.Println(aerr)
	}
	mask := syscall.Umask(0)
	defer syscall.Umask(mask)
	dir := filepath.Dir(absPath)
	err := os.MkdirAll(dir, 0755)
	if err != nil {
		fmt.Println(err)
	}
}
